using Core;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public static class GeneEnumCodeByTable
{
    [MenuItem("Assets/Mini Tools/Conf/生成Table表枚举代码", false, 300)]
    private static void Main()
    {
        EditorUtils.Foreach(ProcessTable, "t:ScriptableObject");

        Debug.Log($"导出完成");
    }

    private static void ProcessTable(string path)
    {
        Debug.Log($"Process... {path}");
        var tbl = AssetDatabase.LoadAssetAtPath<ScriptableObject>(path);
        if (tbl is not IEnumTable enumTable)
        {
            return;
        }

        var parser = new PathParser(path);

        var projName = parser.GetProjName();

        var fileName = parser.FileName;
        fileName = fileName.Substring(3, fileName.IndexOf('.') - 3);

        if (projName.StartsWith("s_"))
        {
            GeneFile($"Core/Sys/Gene", "Core", $"Sys{fileName}", enumTable);
        }
        else
        {
            GeneFile($"Game/{projName}/Common/Gene", projName, fileName, enumTable);
        }
    }

    private static void GeneFile(string projName, string nameSpace, string fileName, IEnumTable tbl)
    {
        var filePath = $"Assets/Code/{projName}/E{fileName}.cs";
        Debug.Log(filePath);

        Utils.File.CreateDirectoryByFilePath(filePath);

        StringBuilder builder = new();

        builder.AppendLine($"namespace {nameSpace}");
        builder.AppendLine($"{{");
        builder.AppendLine($"\tpublic enum E{fileName}");
        builder.AppendLine($"\t{{");
        var list = tbl.GetEnumList();
        foreach (var (id, name) in list)
        {
            builder.AppendLine($"\t\t{Utils.Text.ToUpper(name, 1)} = {id},");
        }

        builder.AppendLine($"\t}}");

        builder.AppendLine($"}}");

        File.WriteAllText(filePath, builder.ToString(), Encoding.UTF8);
    }
}